package com.starbaba.system.user.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Component;

import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.service.CommonService;
import com.starbaba.core.service.CommonServiceSupport;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.system.user.model.UserVO;
import com.starbaba.system.user.model.UserTableVO;
import com.starbaba.system.user.model.getUserModel;
import com.starbaba.system.user.service.userService;

@Component(value="UserServiceImpl")
public class UserServiceImpl  extends CommonServiceSupport implements userService {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5108922671733677590L;
	
	@SuppressWarnings("rawtypes")
    @Override
	public List<UserTableVO> getDataList(int iDisplayStart, int iDisplayLength,
			getUserModel model, PageResponse pageResponse , CommonService server) {
		StringBuffer sf = new StringBuffer();
		sf.append("from UserVO");
		String condition = bulidCondition(model,server);
		sf.append(condition);
		sf.append(" order by userid asc");
		String hql = sf.toString();
		String countHql = "select count(*) " + hql;
		HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(UserVO.class);
		Query query = dao.getSession().createQuery(hql);
		if(iDisplayLength != 0)
		{
			query.setFirstResult(iDisplayStart);
			query.setMaxResults(iDisplayLength);
		}
		//addTimeParm(model,query);
		@SuppressWarnings("unchecked")
        List<UserVO> list = query.list();
		List<UserTableVO> returnList = new ArrayList<UserTableVO>();
		UserTableVO itemVo;
		@SuppressWarnings("unused")
        SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd");
		@SuppressWarnings("unused")
        Map<Long ,UserTableVO> map = new HashMap<Long ,UserTableVO>();
		for(UserVO user :list)
		{
			itemVo = new UserTableVO();
			itemVo.setUserid(user.getUserid());
			itemVo.setComid(user.getComid());
			itemVo.setUsername(user.getUsername());
			itemVo.setStopdate(user.getStopdate());
			returnList.add(itemVo);
		}
		
		Query countQuery = dao.getSession().createQuery(countHql);
		Object obj = countQuery.uniqueResult();
		if(obj instanceof Long)
		{
			int count = ((Long)obj).intValue();
			
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		}
		return returnList;
	}
	
	private String bulidCondition(getUserModel model, CommonService server) {
		StringBuffer condition = new StringBuffer();
		
		String username = model.getUsername();
		if (!StringUtils.isEmpty(username)) {
			condition.append(" where username like '%" + username + "%'");
		}
		
		return condition.toString();
	}
}
